<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>接雨水</title>
</head>

<body>
    <script>
        //思路：获取柱子的最高的索引 H_index
        //从左往右填平 
        //从右往左填平
        let rain = (arr) => {
            let H_index = 0;
            let water = 0;
            let a = 0;
            //获取最高水位的下标
            arr.forEach((val, index) => {
                if (val > a) {
                    H_index = index;
                    a = val;
                }
            });
            // console.log(H_index, a)
            let left = 0;
            //从前往后便利
            for (let i = 0; i <= H_index; i++) {
                water += ((left - arr[i]) > 0 ? (left - arr[i]) : 0);
                left = arr[i] > left ? arr[i] : left;
            }
            let right = 0;
            //从后往前遍历
            for (let j = arr.length - 1; j > H_index; j--) {
                water += ((right - arr[j]) > 0 ? (right - arr[j]) : 0);
                right = arr[j] > right ? arr[j] : right;

            }
            console.log('水的体积：', water);
            return water;
        }
        rain([2, 1, 4, 0, 8, 5, 6, 7, 2]);
        rain([9, 8, 9, 4, 0, 12]);
        rain([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]);
        rain([0, 14, 4, 8, 4, 8]);
    </script>
</body>

</html>